package org.example.springbirthday.utils;

import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 九转苍翎
 * Date: 2025/8/9
 * Time: 12:56
 */
public class SecurityUtils {
    //加密
    public static String encrypt(String inputPassword){
        //生成随机盐值
        String salt = UUID.randomUUID().toString().replaceAll("-", "");
        //(密码+盐值)进行加密
        String finalPassword = DigestUtils.md5DigestAsHex((inputPassword + salt).getBytes());
        return salt + finalPassword;
    }
    //验证
    public static boolean verify(String inputPassword, String sqlPassword){
        if (!StringUtils.hasLength(inputPassword)){
            return false;
        }
        if (sqlPassword == null || sqlPassword.length() != 64){
            return false;
        }
        //取出盐值
        String salt = sqlPassword.substring(0,32);
        //(输入密码 + 盐值)重新生成 加密密码
        String finalPassword = DigestUtils.md5DigestAsHex((inputPassword + salt).getBytes());
        //判断数据库中储存的密码与输入密码是否一致
        return (salt + finalPassword).equals(sqlPassword);
    }
}
